#coding=utf-8
import utils
from decimal import *

def get_soup(code):
    url = 'http://money.finance.sina.com.cn/corp/go.php/vCI_StockStructure/stockid/%s.phtml'%code
    return utils.get_soup(url)

def s2wan(s):
    return int(Decimal(s) * 10000)
    
def get_data_from_table(table):
    #change_date; pulish_date, 变动原因, 总股本, 流通A股,限售A股
    data = []
    cs = table.contents
    
    d = []
    for td in cs[1].contents[1:]:
        d.append(td.string)
    data.append(d)
    
    d = []
    for td in cs[2].contents[1:]:
        d.append(td.string)
    data.append(d)    
    
    d = []
    for td in cs[4].contents[1:]:
        d.append(td.string)
    d = [i.encode('u8') for i in d if i]
    data.append(d)    
    
    d = []
    for td in cs[5].contents[1:]:
        d.append(td.string)
    d = [i[:-2].encode('u8') for i in d if i]
    d = [ s2wan(i) for i in d]
    data.append(d)       
 
    d = []
    for td in cs[7].contents[1:]:
        d.append(td.string)
    d = [i[:-2].encode('u8') for i in d if i]
    d = [  s2wan(i) for i in d]
    data.append(d)        
    
    d = []
    for td in cs[9].contents[1:]:
        d.append(td.string)
    d = [i[:-2].encode('u8') for i in d if i]
    d = [  s2wan(i) for i in d]
    data.append(d)
    
    return zip(*data)        

def get_data(soup):
    #print soup
    data = []
    t = unicode('变动日期', 'u8')
    bds = soup.findAll(text= lambda(x): x.find( t )!=-1)
    #print len(bds)
    
    #i = 0
    for bd in bds:
        #i = i + 1
        table = bd.parent.parent.parent
        #print i
        d = get_data_from_table(table)
        data = data + d
    return data

def get_gbjg(code):
    s = get_soup(code)
    return get_data(s)
